#include <stdio.h>
#include "genlib.h"
#include "graphics.h"
#include "strlib.h"

#define NUM_LEVELS 3
#define MIN_SIDE 0.1

static void drawTriangle(double x, double y, double sideW);
static void drawReversedTriangle(double x, double y, double sideW);
static void divideTriangle(double x, double y, double sideW, int level, string position);

int main() {
	int sideW;
	InitGraphics();
	sideW = GetWindowHeight()/1.2;

	printf("-- Assignment 3 --\n\n");
	drawTriangle(0.1, 0.4, sideW);
	divideTriangle(0.1, 0.4, sideW, NUM_LEVELS, "PEAK_UP");
}

/* Draw a triangle starting at (x,y) with a side width of sideW */
static void drawTriangle(double x, double y, double sideW) {
	MovePen(x, y);
	DrawLine(sideW, sideW);
	DrawLine(sideW, -sideW);
	DrawLine(2*-sideW, 0);
}

/* Draw a reversed triangle starting at (x,y) with a side width of sideW */
static void drawReversedTriangle(double x, double y, double sideW) {
	MovePen(x, y+sideW);
	DrawLine(sideW*2, 0);
	DrawLine(-sideW, -sideW);
	DrawLine(-sideW, sideW);
}

static void divideTriangle(double x, double y, double sideW, int level, string position) {
	if (level == 0 || sideW <= MIN_SIDE)
		return;

	if (StringEqual("PEAK_UP", position)) {
		drawReversedTriangle(x+sideW/2, y, sideW/2);
		divideTriangle(x+sideW/4, y+sideW/4, sideW/2, level-1, "PEAK_DOWN");
		divideTriangle(x, y, sideW/2, level-1, "PEAK_UP");
		divideTriangle(x+sideW, y, sideW/2, level-1, "PEAK_UP");
		divideTriangle(x+sideW/2, y+sideW/2, sideW/2, level-1, "PEAK_UP");
	} else {
		drawTriangle(x+sideW, y, sideW/2);
		divideTriangle(x+sideW, y, sideW/2, level-1, "PEAK_UP");
		divideTriangle(x+sideW/4, y+sideW/4, sideW/2, level-1, "PEAK_DOWN");
		divideTriangle(x+sideW/2*1.5, y-sideW/4, sideW/2, level-1, "PEAK_DOWN");
		divideTriangle(x+sideW*1.25, y+sideW/4, sideW/2, level-1, "PEAK_DOWN");
	}
}